<template>
    <div class="question-edit" style="padding: 25px;">
      <el-card style="min-height: 600px;">
        <template #header>
          <div class="card-header">
            <span>{{ isEdit ? '编辑题目' : '新增题目' }}</span>
            <el-button type="primary" @click="submitForm">提交</el-button>
          </div>
        </template>
  
        <QuestionForm
          ref="formRef"
          :initial-data="formData"
          @submit="handleSubmit"
        />
      </el-card>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, computed } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import QuestionForm from '/@/components/QuestionForm.vue';
  import {
    getQuestionDetail,
    createQuestion,
    updateQuestion,
  } from '/@/api/question/index';
  import type { QuestionDetail } from '/@/types/question';
  
  const route = useRoute();
  const router = useRouter();
  const formRef = ref();
  
  const isEdit = computed(() => route.path.includes('/edit'));
  const questionId = computed(() => {
    return isEdit.value ? Number(route.params.id) : 0;
  });
  
 
  const formData = ref<QuestionDetail>({
    subject_id: 0,
    chapter_id: 0,
    question_type: 1,
    difficulty: 3,
    content: '',
    answer: '',
    analysis: '',
    score: 1,
    options: [
      { option_key: 'A', option_content: '', is_correct: 0 },
      { option_key: 'B', option_content: '', is_correct: 0 }
    ]
  });
  
  // 加载题目详情
  const loadQuestionDetail = async () => {
    if (!isEdit.value) return;
  
    try {
      const res = await getQuestionDetail(questionId.value);
      formData.value = res.data;
    } catch (error) {
      console.error('加载题目详情失败:', error);
      ElMessage.error('加载题目详情失败');
      router.push('/question');
    }
  };
  
  // 提交表单
  const handleSubmit = async (data: QuestionDetail) => {
    try {
      if (isEdit.value) {
        await updateQuestion(questionId.value, data);
        ElMessage.success('更新成功');
      } else {
        await createQuestion(data);
        ElMessage.success('创建成功');
      }
      router.push('/question/list');
    } catch (error) {
      console.error('提交失败:', error);
      ElMessage.error('提交失败');
    }
  };
  
  // 调用子组件提交方法
  const submitForm = () => {
    formRef.value?.submitForm();
  };
  
  onMounted(() => {
    loadQuestionDetail();
  });
  </script>
  
  <style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  </style>